package com.aliyun.auikits.aicall.base;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class SessionHistoryManager {
    private static final String PREFS_NAME = "session_history_prefs";
    private static final String KEY_HISTORY = "session_history";
    private static final Gson gson = new Gson();

    public static void saveSession(Context context, SessionHistory history) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        List<SessionHistory> existing = new ArrayList<>(getSessionHistory(context));
        
        // 移除相同sessionId的旧记录（保持唯一性）
        Iterator<SessionHistory> iterator = existing.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().getSessionId().equals(history.getSessionId())) {
                iterator.remove();
            }
        }
        
        // 添加新记录到列表末尾（保持插入顺序）
        existing.add(history);
        prefs.edit().putString(KEY_HISTORY, gson.toJson(existing)).apply();
    }

    public static List<SessionHistory> getSessionHistory(Context context) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        String json = prefs.getString(KEY_HISTORY, null);
        if (json == null) return new ArrayList<>();
        
        // 修改反序列化类型为ArrayList
        Type type = new TypeToken<ArrayList<SessionHistory>>(){}.getType();
        return gson.fromJson(json, type);
    }

    public static void clearHistory(Context context) {
        context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
                .edit()
                .remove(KEY_HISTORY)
                .apply();
    }
}